package com.xtf.mutids.aop;

import com.xtf.mutids.cache.AreaCache;
import com.xtf.mutids.cache.DataBaseNumCache;
import com.xtf.mutids.constant.DataSourceTypeConstant;
import com.xtf.mutids.datasource.DynamicDataSource;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Random;

@Aspect
@Component
@Slf4j
public class MapperSelectDataSourceAspect {
    @Around("execution(* com.xtf.mutids.mapper.*Mapper.*(..))")
    public Object around(ProceedingJoinPoint joinPoint) {
        Object proceed = null;
        try {
            if (joinPoint.getSignature().getName().startsWith("select")
                    && DataBaseNumCache.getAreaSlaveDataBaseNumMap().get(AreaCache.getAreaCode()) != null) {
                Random r = new Random();
                // 随机选择从库数据源
                DynamicDataSource.setDataSource(
                        AreaCache.getAreaCode() +
                                DataSourceTypeConstant.SLAVE_DB +
                                r.nextInt(DataBaseNumCache.getAreaSlaveDataBaseNumMap().get(AreaCache.getAreaCode())));
            } else {
                if (DataBaseNumCache.getAreaMasterDataBaseNumMap().get(AreaCache.getAreaCode()) != null) {
                    DynamicDataSource.setDataSource(AreaCache.getAreaCode());
                }
            }
            log.info("访问数据源：{}", DynamicDataSource.getDataSource());
            proceed = joinPoint.proceed(joinPoint.getArgs());
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        } finally {
            DynamicDataSource.clearDataSource();
        }

        return proceed;
    }
}
